package com.ibeeking.found.file.rest.controller.v1.feign;


import com.ibeeking.found.common.config.prop.FileOssProp;
import com.ibeeking.found.file.api.common.dto.OssPropDTO;
import com.ibeeking.found.file.api.common.query.FileNameQuery;
import com.ibeeking.found.file.rest.service.IOssFileService;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.file.oss.config.OssProp;
import com.ibeeking.nematos.file.oss.config.OssService;
import com.ibeeking.nematos.file.oss.dto.OssPolicyDto;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author ibeeking
 * 粉丝标签关系
 */
@RestController
@RequestMapping("/b/file/feign/v1")
public class FileFeignController {

    @Resource
    private FileOssProp fileOssProp;
    @Resource
    private IOssFileService ossFileServiceImpl;

    @GetMapping(value = "/ossProp")
    public OssPropDTO ossProp() {
        OssProp bean = SpringBeanUtil.getBean(OssProp.class);
        OssPropDTO ossPropDTO = BeanUtil.convertBean(bean, OssPropDTO.class);
        ossPropDTO.setHost(fileOssProp.getHost());
        return ossPropDTO;
    }

    @GetMapping(value = "/policy")
    public OssPolicyDto policy() {
        OssPolicyDto policy = OssService.policy();
        policy.setPreviewHost(fileOssProp.getHost());
        return policy;
    }

    @PostMapping(value = "/queryFile")
    public void queryFile(@RequestBody FileNameQuery query, HttpServletResponse response) {
        ossFileServiceImpl.queryFile(query.getPath() + query.getFileName(), response);
    }

    @PostMapping(value = "/downloadFile")
    public String downloadFile(@RequestBody FileNameQuery query) {
        return ossFileServiceImpl.download(query.getFileName(), query.getPath());
    }

    @PostMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        OssPolicyDto policy = OssService.policy();
        String fileFullPath = policy.getDir() + file.getOriginalFilename();
        String fileUrl = ossFileServiceImpl.upload(fileFullPath, file.getInputStream());
        LogUtils.info("文件上传成功:" + fileUrl);
        return fileUrl;
    }
}
